package com.dyz.LeetCodeforSwordFingerOffer;

public class SpiralOrder32 {
    public int[] spiralOrder(int[][] matrix) {
        //极值处理
        if(matrix==null||matrix.length==0||matrix[0]==null||matrix[0].length==0){
            return new int[0];
        }
        //设定四个方向
        int m = matrix.length;
        int n = matrix[0].length;
        int left = 0;
        int right = n-1;
        int top = 0;
        int bottom = m-1;
        int[] res = new int[m*n];
        int size = 0;
        while(true){
            //left--> right 不变的式top
            for(int i=left; i<=right;i++){
                res[size++] = matrix[top][i];
            }
            top++;
            if(top>bottom){break;}
            //top->bottom  不变的right
            for (int i=top; i<=bottom;i++){
                res[size++] = matrix[i][right];
            }
            right--;
            if(left>right){break;}

            //从right 向left 不变的是bottom
            for (int i = right; i >=left; i--) {
                res[size++] = matrix[bottom][i];
            }
            bottom--;
            if(top>bottom){break;}

            //从bottom 到 top 不变的是left
            for (int i = bottom; i >=top; i--) {
                res[size++] = matrix[i][left];
            }
            left++;
            if (left>right){break;}
        }
        return res;
    }
}
